<?php

namespace App\Task;

use App\Model\Applet;
use App\Model\DataUserBackhaul;
use GuzzleHttp\Client;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use Psr\Log\LoggerInterface;

class BackhaulDyUserTask
{
    protected LoggerInterface $logger;

//    public static $token = '7FE11418980F94B82110648EC0DAFD2B';
//
    public static $reportUrl = "https://analytics.oceanengine.com/api/v2/conversion";

//    public static $startReportUrl = "https://ad.oceanengine.com/track/activate/";

    public function __construct(protected LoggerFactory $loggerFactory)
    {
        $this->logger = $this->loggerFactory->get('log', 'backhaulDyUser');
    }

    public function execute()
    {
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------获取新注册的用户');
        //获取需要获取任务的视频
        $container = ApplicationContext::getContainer();
        $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('default');
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------获取新注册的用户');
        //获取需要获取任务的视频
        $nowTime = date('Y-m-d H:i:s',time());
        $beforeTime = date('Y-m-d H:i:s',time()-(86400*2));
        $selectTime = date('Y-m-d H:i:s',time()-900);

        $handleKey = 'dy_backhaul_user_or_or_localhost_os_localhost_live';

        try {

            $this->logger->info('获取所有拥有的用户');

            $keyData = $redis->get($handleKey);
            if(!empty($keyData)){

                $this->logger->info('存在处理中的用户进程');
                $this->logger->info(date('Y-m-d H:i:s') . '------------------------结束定时获取用户进行上报');
                return;
            }else{
                $redis->set($handleKey,1);
            }

            $this->logger->info('获取所有拥有的抖音的小程序');

            $appletData = Applet::query()->where(['type' => 2])->select(['id'])->get();
            if($appletData->isNotEmpty()){

//                var_dump($appletData->count());exit();
                foreach ($appletData as $appletDatum) {

                    try {

                        $applet_id = $appletDatum->id;
                        $this->logger->info('查询这个小程序的用户表',[$applet_id]);
                        $userData =Db::table('data_user_'.$applet_id.' as user')
                            ->select(['user.id',
                                'user.xc_open_id',
                                'user.ad_id',
                                'user.is_backhaul',
                                'user.unionid',
                                'user.clue_token',
                                'user.click_id',
                                'data_spread.id as data_spread_id','data_spread.user_type as data_spread_user_type'])
    //                        ->where(['user.is_backhaul' => 'N'])
    //                        ->where(['user.is_handle' => 'N'])
                            ->where('user.spread_id','!=' ,0)
                            ->leftJoin('data_spread','user.spread_id','=','data_spread.id')
                            ->whereBetween('user.dyeing_time',[$selectTime,$nowTime])->get();
                    }catch (\Exception $e){
                        $this->logger->info('查询这个的用户表,错误：',[$e->getMessage()]);
                        continue;
                    }

                    if($userData->isNotEmpty()){
                        $this->logger->info('查询这个的用户表,用户数量为：',[$userData->count()]);
//                        var_dump($userData->count());
                        foreach ($userData as $userDatum){
                            $data_spread_user_type = $userDatum->data_spread_user_type;
                            $spread_id = $userDatum->data_spread_id;

                            //查询用户针对此推广链接回传过
                            $userCount = DataUserBackhaul::query()
                                ->where('user_id', $userDatum->id)
                                ->where('applet_id', $applet_id)
                                ->where('spread_id', $spread_id)
                                ->count('id');
                            if($userCount > 0){
                                continue;
                            }


                            if(empty($userDatum->click_id)) {
                                $this->logger->info('用户没有click ',[$userDatum->id]);
                                Db::table('data_user_'.$applet_id)->where(['id' => $userDatum->id])->update(['is_handle' => 'Y']);
                            }else{
                                $this->logger->info('用户上报注册ID ',[$userDatum->id]);
                                $clue_token = '';
                                $unionid = '';
                                $xc_open_id = '';
                                $click_id = $userDatum->click_id;
                                //普通用户
                                $registerData = $this->uploadRegister($click_id,$data_spread_user_type);
                                if($registerData){
                                    $this->logger->info('用户上报计划成功，存入关联表 ',[$userDatum->id]);
                                    DataUserBackhaul::create([
                                        'applet_id' => $applet_id,
                                        'user_id' => $userDatum->id,
                                        'spread_id' => $spread_id,
                                        'clue_token' => $clue_token,
                                        'unionid' => $unionid,
                                        'xc_open_id' => $xc_open_id,
                                        'click_id' => $click_id,
                                        'user_type' => $data_spread_user_type,
                                    ]);
                                    Db::table('data_user_'.$applet_id)->where(['id' => $userDatum->id])->update(['is_handle' => 'Y','is_backhaul' => 'Y']);
                                }else{
                                    $this->logger->error('用户上报计划失败，部分值为空',[$click_id]);
                                }
                            }
//                            break;
                        }
                    }else{
                        $this->logger->error('没有用户需要上报');
                    }
                }
            }else{
                $this->logger->info('没有微信的小程序');
            }
            $redis->del($handleKey);
        }catch (\Exception $e){
            $redis->del($handleKey);
            $this->logger->error('请求上报出现问题|错误：' . $e->getLine() . '|' . $e->getMessage());
        }
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------结束获取新注册的用户');
    }
//    function getMillisecondTimeStamp() {
//        list($msec, $sec) = explode(' ', microtime());
//        return (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
//    }

    public function uploadRegister($clickid,$user_type){
        //普通用户

        if(empty($clickid)){
            return false;
        }
        $params = [
            "context" =>
                ["ad" =>[
                    'callback' => $clickid
                ],
                ],
            "event_type"  => "active",
            "timestamp" => time()*1000
        ];
        $linkUrl = self::$reportUrl;
        $this->logger->info('请求上报数据：'.PHP_EOL.var_export(['result' => $params], true));
        $this->logger->info('请求上报Url：'.$linkUrl);
        //开始上传
        $result  = $this->request($params, $linkUrl,'POST');
        if($result['code'] == 0 ){
            $this->logger->info('调用上报接口成功 返回数据：'.PHP_EOL.var_export(['result' => $result], true));
            return true;
        }else{
            $this->logger->error('调用上报接口失败 返回数据：'.PHP_EOL.var_export(['result' => $result], true));
        }

        return false;
    }

    /**
     * 传入数组进行HTTP POST请求
     */
    function request(array $params, string $url,string $method)
    {
        $client   = new Client([
            'timeout' => 3
        ]);
        $headers       =['Content-Type' => 'application/json;charset=utf-8', 'Accept' => 'application/json','Accept-Charset' => 'utf-8'];
        $requestParams = [
            'headers' => $headers,
        ];
        if ($method == 'GET') {
            $requestParams['query'] = $params;
        } else {
            $requestParams['json'] = $params;
        }
//        var_dump($requestParams);
        $response = $client->request($method,$url, $requestParams);
        if ($response->getStatusCode() !== 200) {
            return '';
        }
        $result   = $response->getBody()->getContents();
        $resultArr = json_decode($result,true);
        return $resultArr;

    }
}